<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample</title>
<meta name="viewport"
            content="width=device-width, initial-scale=1.0">
<meta name="HandheldFriendly" content="true">
</head>
<body>
<canvas id="myCanvas" width="300" height="150"
        style="border:1px dashed #c3c3c3;">
   这里放置的内容用于浏览器不支持Canvas的情况
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
if (canvas && canvas.getContext) {
   var cxt = canvas.getContext("2d");
   // 绘制矩形
   var grd = cxt.createLinearGradient(0,0,150,75);
   grd.addColorStop(0,"#FF0000");
   grd.addColorStop(1,"#00FF00");
   cxt.fillStyle = grd;
   cxt.rect(0,0,150,75);
   cxt.fill();
}

// 定义canvas的鼠标mousedown事件
function mousedownHandler(event){
   // 获取鼠标单击位置
   var x = event.clientX - canvas.offsetLeft;
   var y = event.clientY - canvas.offsetTop;
   var cxt = canvas.getContext("2d");
   // 检测是否单击在矩形内，如果在矩形内就清空画布
   if (cxt.isPointInPath(x, y))
      cxt.clearRect(0, 0, canvas.width, canvas.height);
}
canvas.addEventListener("mousedown", mousedownHandler, false);
</script>
</body>
</html>
